package com.sjb.cp.manager;

import cn.hutool.core.io.FileUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import com.sjb.cp.config.COSConfig;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:sjb
 * @CreateTime:2024-12-12
 * @Description: 通用的对象存储操作
 * @Version：1.0
 */
@Component
public class CosManager {

    @Resource
    private COSConfig cosConfig;

    @Resource
    private COSClient cosClient;


    /**
     * 上传对象
     * @param key
     * @param file
     * @return
     */
    public PutObjectResult putObject(String key, File file){
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucket(), key, file);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 下载对象
     * @param key
     * @return
     */
    public COSObject getObject(String key){
        GetObjectRequest getObjectRequest = new GetObjectRequest(cosConfig.getBucket(), key);
        return cosClient.getObject(getObjectRequest);
    }

    /**
     * 上传对象（附带图片信息）
     * @return
     */
    public PutObjectResult putPictureObject(String key, File file){
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucket(), key, file);
        // 对图片进行处理
        PicOperations picOperations = new PicOperations();
        // 1 表示返回原图信息
        picOperations.setIsPicInfo(1);
        List<PicOperations.Rule> listRules = new ArrayList<PicOperations.Rule>();
        // 图片压缩 转成webP格式
        String webKey = FileUtil.mainName(file) + ".webp";
        PicOperations.Rule rule = new PicOperations.Rule();
        rule.setBucket(cosConfig.getBucket());
        rule.setFileId(webKey);
        rule.setRule("imageMogr2/format/webp");
        listRules.add(rule);
        picOperations.setRules(listRules);
        // 构造处理参数
        putObjectRequest.setPicOperations(picOperations);
        // 缩略图处理
        if (file.length() > 2 *1024){
            PicOperations.Rule thumbnailRule = new PicOperations.Rule();
            thumbnailRule.setBucket(cosConfig.getBucket());
            String thumbnailKey = FileUtil.mainName(key) + "_thumbnail." + FileUtil.getSuffix(key);
            thumbnailRule.setFileId(thumbnailKey);
            // 缩放规则 /thumbnail/<Width>x<Height>>（如果大于原图宽高，则不处理）
            thumbnailRule.setRule(String.format("imageMogr2/thumbnail/%sx%s>", 128, 128));
            listRules.add(thumbnailRule);
        }
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 删除对象
     * @param key
     * @throws CosClientException
     */
    public void deleteObject(String key) throws CosClientException {
        cosClient.deleteObject(cosConfig.getBucket(), key);
    }
}
